package com.cheyun.netsalev3.tencenttim.profile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.tencenttim.BaseActivity;
import com.cheyun.netsalev3.tencenttim.profile.clipimagedemo.ClipImageLayout;
import com.cheyun.netsalev3.tencenttim.profile.clipimagedemo.CustomProgressDialog;
import com.cheyun.netsalev3.tencenttim.utils.Constants;
import com.cheyun.netsalev3.tencenttim.utils.DemoLog;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;

/**
 * 裁剪图片的Activity
 * 
 * @ClassName: CropImageActivity
 * @Description:
 * @author xiechengfa2000@163.com
 * @date 2015-5-8 下午3:39:22
 */
public class ClipImageActivity extends BaseActivity implements OnClickListener {
	public static final String RESULT_PATH = "crop_image";
	private static final String pp = "path";
	private ClipImageLayout mClipImageLayout = null;
	private  Dialog  builder;
	private ProgressBar progressBar;
	private TextView percentText;
	private String name = "order";
	private CustomProgressDialog dialog;
	CustomProgressDialog utils;

	private static final String TAG = ClipImageActivity.class.getSimpleName();

	private String END_POINT = "http://oss-cn-hangzhou.aliyuncs.com";

//	public String HTTP_SERVER_IMAGE_URL = "http://img01.kfenxiang.cn/";
//	private String ACCESS_KEY = "LTAIWeXBATRK3oMB";
//	private String ACCESS_SECRET = "JLEo8uxi0k8Fs00WJHRyDpN57ewPBs";
//	private String BUCKET_NAME = "cheyun-kfenxiang";


	private String ACCESS_KEY = "LTAI4FoDY8YtB32RzkLDfhU6";
	private String ACCESS_SECRET = "fhECIeU3HMNAnk12x118hEkptWgGqs";
	private String BUCKET_NAME = "cheyun-h5";
	public String HTTP_SERVER_IMAGE_URL = "https://h5img.new4s.com/";

	private String from = "";

	String path;
	private Handler mHandler = new Handler() {
		public void handleMessage (Message msg) {//此方法在ui线程运行

		}
	};

	public static void startActivity(Activity activity, String path, int code) {
		Intent intent = new Intent(activity, ClipImageActivity.class);
		intent.putExtra(pp, path);
		activity.startActivityForResult(intent, code);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.crop_image_layout);
		initView();
	}

	protected void initView() {
		mClipImageLayout = (ClipImageLayout) findViewById(R.id.clipImageLayout);
		path = getIntent().getStringExtra(pp);
		name = getIntent().getStringExtra("name");
		String type = getIntent().getStringExtra("type");
		if(getIntent().hasExtra("from")){
			from = getIntent().getStringExtra("from");
		}
		mClipImageLayout.settype(ClipImageActivity.this,Integer.parseInt(type));

		// 有的系统返回的图片是旋转了，有的没有旋转，所以处理
		int degreee = readBitmapDegree(path);
		Bitmap bitmap = createBitmap(path);
		if (bitmap != null) {
			if (degreee == 0) {
				mClipImageLayout.setImageBitmap(bitmap);
			} else {
				mClipImageLayout.setImageBitmap(rotateBitmap(degreee, bitmap));
			}
		} else {
			//finish();
		}
		findViewById(R.id.okBtn).setOnClickListener(this);
		findViewById(R.id.cancleBtn).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.okBtn) {
			Bitmap bitmap = mClipImageLayout.clip();
			String path = Environment.getExternalStorageDirectory() + "/";
			saveBitmap(bitmap, path);
			dialog = new CustomProgressDialog(ClipImageActivity.this,"",R.drawable.uploadframe);
			dialog.show();
			if(name.contains("order")) {
				toUploadFile(path);
			}else{
				dialog.cancel();
				finish();
			}
			/*Intent intent = new Intent();
			intent.putExtra(RESULT_PATH, path);
			setResult(RESULT_OK, intent);*/
		}else{
			if(dialog!=null){
				dialog.cancel();
			}
			finish();
		}
		//finish();
	}

	private void toUploadFile(String path){
		ossImg(path);
	}

	private void ossImg(String pigpath) {
		DemoLog.i("ClipImageActivity","start ossimg");
		// 构造上传请求
		// 明文设置secret的方式建议只在测试时使用，更多鉴权模式请参考后面的`访问控制`章节
		OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(ACCESS_KEY, ACCESS_SECRET);
		OSS oss = new OSSClient(getApplicationContext(), END_POINT, credentialProvider);
		PutObjectRequest put = new PutObjectRequest(BUCKET_NAME, name, pigpath + name + ".jpg");
		showDialogs();
		// 异步上传时可以设置进度回调
		put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
			@Override
			public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
				Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
				final int count = (int) ((currentSize * 1.0 / totalSize) * 100);
				percentText.post(new Runnable() {//另外一种更简洁的发送消息给ui线程的方法。
					@Override
					public void run() {//run()方法会在ui线程执行
						percentText.setText(count + "%" + "正在上传...");
					}
				});
				progressBar.post(new Runnable() {
					@Override
					public void run() {
						progressBar.setProgress(count);
					}
				});
			}
		});

		OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
			@Override
			public void onSuccess(PutObjectRequest request, PutObjectResult result) {
				String imgUrl = HTTP_SERVER_IMAGE_URL + name;
				builder.cancel();
				if(from.equals("order")){
					uploadOrderImg(imgUrl);
				}else{
					uploadTouxiang(imgUrl);
				}
			}

			@Override
			public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
				// 请求异常
				if (clientExcepion != null) {
					// 本地异常如网络异常等
					clientExcepion.printStackTrace();

				}
				if (serviceException != null) {
					// 服务异常
					Log.e("ErrorCode", serviceException.getErrorCode());
					Log.e("RequestId", serviceException.getRequestId());
					Log.e("HostId", serviceException.getHostId());
					Log.e("RawMessage", serviceException.getRawMessage());
				}
			}
		});
//		 task.cancel(); // 可以取消任务
//		 task.waitUntilFinished(); // 可以等待直到任务完成
	}

	private void uploadTouxiang(final String faceimg){
		System.out.println("上传头像地址："+faceimg);
		HashMap<String, Object> hashMap = new HashMap<>();
		// 头像
		if (!TextUtils.isEmpty(faceimg)) {
			hashMap.put(TIMUserProfile.TIM_PROFILE_TYPE_KEY_FACEURL, faceimg);
		}
		TIMFriendshipManager.getInstance().modifySelfProfile(hashMap, new TIMCallBack() {
			@Override
			public void onError(int i, String s) {
				ToastUtil.toastShortMessage("Error code = " + i + ", desc = " + s);
			}

			@Override
			public void onSuccess() {
				DemoLog.i(TAG, "modifySelfProfile success");
				ToastUtil.toastShortMessage("修改成功");
				SharedPreferences shareInfo = getSharedPreferences(Constants.USERINFO, Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = shareInfo.edit();
				editor.putString(Constants.ICON_URL, faceimg);
				editor.commit();
				finish();
			}
		});
	}

	private void uploadOrderImg(final String faceimg){
		System.out.println("上传凭证地址："+faceimg);
//		SharedPreferences shareInfo = getSharedPreferences(Constants.USERINFO, Activity.MODE_PRIVATE);
//		SharedPreferences.Editor editor = shareInfo.edit();
//		editor.putString(Constants.ICON_URL, faceimg);
//		editor.commit();
		LiveEventBus.get().with("uploadOrderImg").postValue(faceimg);
		finish();
	}

	public void showDialogs() {
		builder = new Dialog(ClipImageActivity.this);
		builder.show();
		//builder.getWindow().setBackgroundDrawable(new ColorDrawable(0)); 
		Window window = builder.getWindow();
		window.setContentView(R.layout.dialog_publish);
		builder.setCanceledOnTouchOutside(true);
		// 为确认按钮添加事件,执行退出应用操作  
		progressBar = (ProgressBar) window.findViewById(R.id.progress);
		percentText = (TextView) window.findViewById(R.id.txt_percent);
		((ImageView) window.findViewById(R.id.btn_cancel)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				builder.dismiss();
				finish();
			}
		});
		builder.setCanceledOnTouchOutside(false);
	}
 
	private void saveBitmap(Bitmap bitmap, String path) {
		File f = new File(path,name+".jpg");
		if (f.exists()) {
			f.delete();
		}
		FileOutputStream fOut = null;
		try {
			f.createNewFile();
			fOut = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
			if(utils!=null&&utils.isShowing()){
				utils.cancel();
			}
		} catch (IOException e1) {
			Log.e(TAG,e1.getMessage());
		} finally {
			try {
				if (fOut != null)
					fOut.close();
			} catch (IOException e) {
				Log.e(TAG,e.getMessage());
			}
		}
	}

	/**
	 * 创建图片
	 * 
	 * @param path
	 * @return
	 */
	private Bitmap createBitmap(final  String path) {
		if (path == null) {
			return null;
		}
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inSampleSize = 1;
		opts.inJustDecodeBounds = false;// 这里一定要将其设置回false，因为之前我们将其设置成了true
		opts.inPurgeable = true;
		opts.inInputShareable = true;
		opts.inDither = false;
		opts.inPurgeable = true;
		FileInputStream is = null;
		Bitmap bitmap = null;
		try {
			is = new FileInputStream(path);
			bitmap = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
		} catch (IOException e) {
			Log.e(TAG,e.getMessage());
		} finally {
			try {
				if (is != null) {
					is.close();
					is = null;
				}
			} catch (IOException e) {
				Log.e(TAG,e.getMessage());
			}
		}
		return bitmap;
	}

	// 读取图像的旋转度
	private int readBitmapDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			Log.e(TAG,e.getMessage());
		}
		return degree;
	}

	// 旋转图片
	private Bitmap rotateBitmap(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, false);
		return resizedBitmap;
	}
}
